package com.qeado.content.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.qeado.admin.common.BaseConstData;
import com.qeado.common.UploadFileLocation;
import com.qeado.common.helper.AttributeHelper;
import com.qeado.content.model.BdTypeCode;
import com.qeado.content.model.KindTypeCode;
import com.qeado.content.model.Product;
import com.qeado.content.model.RkTypeCode;
import com.qeado.content.model.UnitTypeCode;
import com.qeado.content.service.ProductManageService;

@Controller
public class ProductManageController {
		
	    @Autowired
		private ProductManageService productManageService;
	    
	    @RequestMapping("/prodInfoManage.ac")
		public String  showProductManage(HttpServletRequest request){
			AttributeHelper.removeSessionAttribute(request, "T_");
	    	List<BdTypeCode>   bdTypeList   = this.productManageService.getAllBrandTypeCode();
	    	List<KindTypeCode> kdTypeList   = this.productManageService.getAllKindTypeCode();
	    	List<RkTypeCode>   rkTypeList   = this.productManageService.getAllRankTypeCode();
	     	List<UnitTypeCode> unitTypeList = this.productManageService.getAllUnitTypeCode();
	     	request.getSession().setAttribute("T_bdTypeList", bdTypeList);
	     	request.getSession().setAttribute("T_kindTypeList", kdTypeList);
	     	request.getSession().setAttribute("T_rkTypeList", rkTypeList);  	
	     	request.getSession().setAttribute("T_unitTypeCodeList", unitTypeList);
			return "content/product_manage";
		}
	    
	    @RequestMapping("/backToProdFind.ac")
	    public String  backToProdFind(){ 	
			return "content/product_manage";
		}
	    
	    @RequestMapping("/prodFind.ac")
	    public ModelAndView  findProduct(HttpServletRequest req, Product pro){ 	
	    	List<Product> prodList = this.productManageService.getProductListByCondition(pro);
			return new  ModelAndView("content/product_manage","prodList",prodList);
		} 
	    
	    @RequestMapping("/deleteProd.ac")
	    public ModelAndView deleProductById(Product p){
	    	this.productManageService.deleProductListById(p);
	    	List<Product> prodList = this.productManageService.getProductListByCondition(null);
			return new  ModelAndView("content/product_manage","prodList",prodList);
	    }
	    
	    @RequestMapping("/prodNew.ac")
	    public ModelAndView newProduct(HttpServletRequest req, String id){
            Product p = this.productManageService.searchProductById(id);
	    	return new  ModelAndView("content/product_detail","product",p);
	    }
	    
	    @RequestMapping("/getProdPhoto.ac")
		public void getProdPhoto(HttpServletRequest request, HttpServletResponse response, String fileName, String type) throws UnsupportedEncodingException {
			fileName = URLEncoder.encode(fileName,"UTF-8");
		    response.addHeader("Content-Disposition","attachment;filename=" + fileName);
		    OutputStream output = null;
		    FileInputStream fis = null;
		    try {
		        output = response.getOutputStream();
		        File file = new File(UploadFileLocation.BASE_DIR + "\\product\\" + type + "\\" +fileName);
		        fis = new FileInputStream(file);
		        byte[] b = new byte[1024];
		        int i = 0;
		        while((i = fis.read(b)) > 0) {
		            output.write(b, 0, i);
		        }
		        output.flush();
		    } catch(Exception e) {
		        e.printStackTrace();
		    } finally {
		        if(fis != null) { 
		        	try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		        }
		        if(output != null) {
		        	try {
						output.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		        }
		    }
		}
	    
	    @RequestMapping("/prodSave.ac")
	    public String saveNewProduct(HttpServletRequest request, Product product){
	    	product.setCreator(request.getSession().getAttribute(BaseConstData.USER_ID).toString());
	    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			MultipartFile file = multipartRequest.getFile("brandFile");
			MultipartFile prodFile = multipartRequest.getFile("prodFile");
			if(!prodFile.isEmpty()) {
				String imgName = getFileNameByTime(prodFile.getOriginalFilename());
				try {
					String path = UploadFileLocation.BASE_DIR + "\\product\\prod" ;
					File uploadedFile = new File(path + "\\" + imgName);
					int v;         
					BufferedInputStream inputStream = new BufferedInputStream(prodFile.getInputStream());     
					FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
					byte [] bytes = new byte[1024];     
					while((v = inputStream.read(bytes)) > 0){     
					    outputStream.write(bytes, 0, v);     
					}     
					outputStream.close();     
					inputStream.close();	
				} catch (Exception e) {
					e.printStackTrace();
				}
				product.setFileName(imgName);
			}
			if(!file.isEmpty()) {
				String imgName = getFileNameByTime(file.getOriginalFilename());
				try {
					String path = UploadFileLocation.BASE_DIR + "\\product\\brand" ;
					File uploadedFile = new File(path + "\\" + imgName);
					int v;         
					BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());     
					FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
					byte [] bytes = new byte[1024];     
					while((v = inputStream.read(bytes)) > 0){     
					    outputStream.write(bytes, 0, v);     
					}     
					outputStream.close();     
					inputStream.close();	
				} catch (Exception e) {
					e.printStackTrace();
				}
				product.setBrandPic(imgName);
			}
	    	this.productManageService.insertNewProduct(product);
	    	return "content/product_detail";
	    }
	    
	    @RequestMapping("/prodUpdate.ac")
	    public String updateProduct(HttpServletRequest request, Product product){
	    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			MultipartFile file = multipartRequest.getFile("brandFile");
			MultipartFile prodFile = multipartRequest.getFile("prodFile");
			if(!prodFile.isEmpty()) {
				String imgName = getFileNameByTime(prodFile.getOriginalFilename());
				try {
					String path = UploadFileLocation.BASE_DIR + "\\product\\prod" ;
					if(!"".equals(product.getFileName())) {
						File oldFile = new File(path + "\\" + product.getFileName());
						oldFile.delete();
					}
					File uploadedFile = new File(path + "\\" + imgName);
					int v;         
					BufferedInputStream inputStream = new BufferedInputStream(prodFile.getInputStream());     
					FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
					byte [] bytes = new byte[1024];     
					while((v = inputStream.read(bytes)) > 0){     
					    outputStream.write(bytes, 0, v);     
					}     
					outputStream.close();     
					inputStream.close();	
				} catch (Exception e) {
					e.printStackTrace();
				}
				product.setFileName(imgName);
			}
			if(!file.isEmpty()) {
				String imgName = getFileNameByTime(file.getOriginalFilename());
				try {
					String path = UploadFileLocation.BASE_DIR + "\\product\\brand" ;
					if(!"".equals(product.getBrandPic())) {
						File oldFile = new File(path + "\\" + product.getBrandPic());
						oldFile.delete();
					}
					File uploadedFile = new File(path + "\\" + imgName);
					int v;         
					BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());     
					FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
					byte [] bytes = new byte[1024];     
					while((v = inputStream.read(bytes)) > 0){     
					    outputStream.write(bytes, 0, v);     
					}     
					outputStream.close();     
					inputStream.close();	
				} catch (Exception e) {
					e.printStackTrace();
				}
				product.setBrandPic(imgName);
			}
	    	this.productManageService.updateProduct(product);
	    	return "content/product_detail";
	    }
	    
	    @RequestMapping("/searchProdOwner.ac")
	    public String searchProdOwner() {
	    	return "content/prod_owner_search";
	    }
	    
	    @RequestMapping("/searchUserInfoFromProd.ac")
	    public ModelAndView searchUserInfoFromProd(String prodOwnerName, String email) {
	    	List<Map<String,String>> userInfoList = productManageService.searchUserInfoFromProd(prodOwnerName, email);
	    	return new ModelAndView("content/prod_owner_search", "userInfoList", userInfoList);
	    }
	    
	    private synchronized String getFileNameByTime(String input){
	        int index = input.lastIndexOf(".");
	        return System.currentTimeMillis() + input.substring(index);
	    }
}
